import * as fs from 'fs'
import * as path from 'path'
import { Command, flags } from '@oclif/command'
import cli from 'cli-ux'

class FilenameRandomPrefixCli extends Command {

  static description = '文件名随机前缀生成工具'

  static flags = {
    version: flags.version({ char: 'v' }),
    help: flags.help({ char: 'h' }),
    dir: flags.string({ char: 'd', required: true, description: '目录路径' }),
    separator: flags.string({ char: 's', required: false, default: '@@@', description: '分隔符' }),
    remove: flags.boolean({ char: 'r', required: false, default: false, description: '是否移除随机前缀' })
  }

  async run() {
    const { flags } = this.parse(FilenameRandomPrefixCli)
    console.log('flags', flags)

    if (!fs.existsSync(flags.dir)) {
      throw new Error(`不存在的路径：${flags.dir}`)
    }
    if (!fs.statSync(flags.dir).isDirectory()) {
      throw new Error(`必须是一个文件夹：${flags.dir}`)
    }

    console.time('耗时')

    let filenames = fs.readdirSync(flags.dir)

    const bar = cli.progress({ format: '进度 [{bar}] {percentage}% | 预计剩余时间: {eta}s' })
    bar.start(filenames.length, 0)

    for (let i = 0; i < filenames.length; i++) {
      let oldPath = path.join(flags.dir, filenames[i])
      if (fs.statSync(oldPath).isFile()) {
        let newname: string
        if (flags.remove) {
          let [prefix, ...parts] = filenames[i].split(flags.separator)
          newname = parts.length > 0 ? parts.join(flags.separator) : prefix
        } else {
          newname = `${Math.floor(Math.random() * filenames.length)}${flags.separator}${filenames[i]}`
        }
        fs.renameSync(oldPath, path.join(flags.dir, newname))
      }
      bar.update(i + 1)
    }

    bar.stop()
    console.timeEnd('耗时')

  }

}

export = FilenameRandomPrefixCli
